<template>
  <div class="table-container">
    <h2>分片加载table</h2>
    <el-table :data="displayData" style="width: 100%">
      <el-table-column prop="id" label="编号" width="80"> </el-table-column>
      <el-table-column prop="name" label="姓名"> </el-table-column>
      <el-table-column prop="age" label="年龄"> </el-table-column>
      <el-table-column prop="gender" label="性别"> </el-table-column>
    </el-table>
    <div v-if="loading" class="loading">加载中...</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
      chunkSize: 100,
      displayData: [], // 当前已渲染数据
      loading: false, // 加载状态
      currentIndex: 0, // 当前索引
    };
  },
  async created() {
    this.getData();
    // this.loadMore();
  },
  methods: {
    async getData() {
      const res = await this.$http.get("/user/list");
      console.log("res", res);
      this.tableData = res.data;
      this.startChunkRender();
    },
    startChunkRender() {
      let index = 0;
      const renderNext = () => {
        const chunk = this.tableData.slice(index, index + this.chunkSize);
        this.displayData = [...this.displayData, ...chunk]; // 追加数据
        index += this.chunkSize;
        if (index < this.tableData.length) {
          requestAnimationFrame(renderNext); // 下一帧继续渲染
        }
      };
      renderNext();
    },
    async loadMore() {
      if (this.currentIndex >= this.tableData.length) return;
      this.loading = true;
      // 模拟异步加载（关键：通过延迟让 loading 状态可见）
      await new Promise((resolve) => setTimeout(resolve, 500)); // 500ms 延迟
      const nextBatch = this.tableData.slice(
        this.currentIndex,
        this.currentIndex + this.chunkSize
      );
      this.displayData = [...this.displayData, ...nextBatch];
      this.currentIndex += this.chunkSize;
      this.loading = false;
    },
    handleScroll(e) {
      const { scrollTop, clientHeight, scrollHeight } = e.target;
      const threshold = 50;
      if (scrollHeight - (scrollTop + clientHeight) < threshold) {
        this.loadMore();
      }
    },
  },
};
</script>
<style scoped>
.table-container {
  height: 100vh; /* 或使用 calc(100vh - 200px) 等动态高度 */
  overflow-y: auto;
}
.loading {
  text-align: center;
  padding: 10px;
  color: #999;
}
</style>
